package com.qeeyou.apps.android.craftsman.activity.order;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.qeeyou.apps.android.craftsman.R;
import com.qeeyou.apps.android.craftsman.common.Contants;
import com.qeeyou.apps.android.craftsman.po.OrderDetailInfo;
import com.qeeyou.apps.android.craftsman.po.OrderInfo;
import com.qeeyou.apps.android.craftsman.po.OrderItemInfo;
import com.qeeyou.apps.android.craftsman.po.OrderMasterInfo;
import com.qeeyou.apps.android.craftsman.po.OrderRemarkInfo;
import com.qeeyou.apps.android.craftsman.po.OrderServiceInfo;
import com.qeeyou.apps.android.craftsman.service.AppService;
import com.qeeyou.apps.android.craftsman.utils.ImageLoader;
import com.qeeyou.apps.android.craftsman.view.CustomLoadingDialog;
import com.qeeyou.apps.android.craftsman.view.OrderStatusButton;

import java.util.HashMap;
import java.util.Map;

public class OrderDetailActivity extends Activity {

    private ImageView btnBack;
    private TextView txtvTitle;
    private TextView txtvStatus;
    private LinearLayout llayoutStatus;                  //订单状态
    private LinearLayout llayoutOrder;                   //工单信息
    private LinearLayout llayoutRemark;                  //备注信息
    private LinearLayout llayoutInstall;                 //安装人员信息
    private LinearLayout llayoutService;                 //服务过程

    private CustomLoadingDialog mLoadingDialog;

    private OrderInfo mOrderInfo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order_detail);

        Intent intent = getIntent();
        if(intent != null && intent.getSerializableExtra("orderInfo") != null) {
            mOrderInfo = (OrderInfo) intent.getSerializableExtra("orderInfo");
        }

        setView();
        setEvent();
    }

    private void setView() {
        btnBack = (ImageView) this.findViewById(R.id.btnBack4OrderDetail);
        txtvTitle = (TextView) this.findViewById(R.id.txtvTitle4OrderDetail);
        txtvStatus = (TextView) this.findViewById(R.id.txtvStatus4OrderDetail);
        llayoutStatus = (LinearLayout) this.findViewById(R.id.llayoutStatus4OrderDetail);
        llayoutOrder = (LinearLayout) this.findViewById(R.id.llayoutOrder4OrderDetail);
        llayoutRemark = (LinearLayout) this.findViewById(R.id.llayoutRemark4OrderDetail);
        llayoutInstall = (LinearLayout) this.findViewById(R.id.llayoutInstall4OrderDetail);
        llayoutService = (LinearLayout) this.findViewById(R.id.llayoutService4OrderDetail);
    }

    private void setEvent() {

        btnBack.setOnClickListener(onBackClickListener);

        //加载信息
        String orderStatus = null;
        String commentStatus = null;
        String orderId = null;
        if(mOrderInfo != null) {
            orderStatus = mOrderInfo.getOrderstatus();
            commentStatus = mOrderInfo.getCommentstatus();
            orderId = mOrderInfo.getOrderid();
        }
        //显示订单信息
        showOrderInfo(orderStatus, commentStatus);
        if(orderId != null) {
            //获取订单信息
            String[] params = new String[]{orderId};
            new GetOrderDetailInfo().execute(params);
        }

    }

    //返回
    private View.OnClickListener onBackClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            OrderDetailActivity.this.finish();
        }
    };

    //显示订单信息
    private void showOrderInfo(String orderStatus, String commentStatus) {
        OrderStatusButton btnStatus1 = (OrderStatusButton)llayoutStatus.getChildAt(0);
        OrderStatusButton btnStatus2 = (OrderStatusButton)llayoutStatus.getChildAt(2);
        OrderStatusButton btnStatus3 = (OrderStatusButton)llayoutStatus.getChildAt(4);
        OrderStatusButton btnStatus4 = (OrderStatusButton)llayoutStatus.getChildAt(6);
        btnStatus4.setText("已评价");
        if (orderStatus == null || orderStatus.trim().equalsIgnoreCase("")) {
            txtvTitle.setText("订单详情");
            btnStatus1.setImage(R.drawable.ic_order_status_doing);
            btnStatus2.setImage(R.drawable.ic_order_status_todo);
            btnStatus3.setImage(R.drawable.ic_order_status_todo);
            btnStatus4.setImage(R.drawable.ic_order_status_todo);
            txtvStatus.setText("待接单");
            //显示信息
            llayoutInstall.setVisibility(View.GONE);
            llayoutService.setVisibility(View.GONE);
        } else if(orderStatus.trim().equalsIgnoreCase(Contants.ORDER_STATUS_TODO)) {
            txtvTitle.setText("待接单详情");
            btnStatus1.setImage(R.drawable.ic_order_status_doing);
            btnStatus2.setImage(R.drawable.ic_order_status_todo);
            btnStatus3.setImage(R.drawable.ic_order_status_todo);
            btnStatus4.setImage(R.drawable.ic_order_status_todo);
            txtvStatus.setText("待接单");
            //显示信息
            llayoutInstall.setVisibility(View.GONE);
            llayoutService.setVisibility(View.GONE);
        } else if (orderStatus.trim().equalsIgnoreCase(Contants.ORDER_STATUS_DOING)) {
            txtvTitle.setText("待安装详情");
            btnStatus1.setImage(R.drawable.ic_order_status_done);
            btnStatus2.setImage(R.drawable.ic_order_status_doing);
            btnStatus3.setImage(R.drawable.ic_order_status_todo);
            btnStatus4.setImage(R.drawable.ic_order_status_todo);
            txtvStatus.setText("待安装");
            //显示信息
            llayoutInstall.setVisibility(View.VISIBLE);
            llayoutService.setVisibility(View.GONE);
        } else if (orderStatus.trim().equalsIgnoreCase(Contants.ORDER_STATUS_DONE)) {
            if(commentStatus != null && commentStatus.equalsIgnoreCase("1")) {
                txtvTitle.setText("已完成详情");
                btnStatus1.setImage(R.drawable.ic_order_status_done);
                btnStatus2.setImage(R.drawable.ic_order_status_done);
                btnStatus3.setImage(R.drawable.ic_order_status_done);
                btnStatus4.setImage(R.drawable.ic_order_status_doing);
                txtvStatus.setText("已评价");
            } else {
                txtvTitle.setText("已完成详情");
                btnStatus1.setImage(R.drawable.ic_order_status_done);
                btnStatus2.setImage(R.drawable.ic_order_status_done);
                btnStatus3.setImage(R.drawable.ic_order_status_doing);
                btnStatus4.setImage(R.drawable.ic_order_status_todo);
                txtvStatus.setText("已完成");
            }
            llayoutInstall.setVisibility(View.VISIBLE);
            llayoutService.setVisibility(View.VISIBLE);
        } else if (orderStatus.trim().equalsIgnoreCase(Contants.ORDER_STATUS_CANCEL)) {
            txtvTitle.setText("已完成详情");
            btnStatus1.setImage(R.drawable.ic_order_status_done);
            btnStatus2.setImage(R.drawable.ic_order_status_done);
            btnStatus3.setImage(R.drawable.ic_order_status_done);
            btnStatus4.setImage(R.drawable.ic_order_status_doing);
            btnStatus4.setText("已取消");
            txtvStatus.setText("已取消");
            llayoutInstall.setVisibility(View.VISIBLE);
            llayoutService.setVisibility(View.VISIBLE);
        } else {
            txtvTitle.setText("订单详情");
            btnStatus1.setImage(R.drawable.ic_order_status_doing);
            btnStatus2.setImage(R.drawable.ic_order_status_todo);
            btnStatus3.setImage(R.drawable.ic_order_status_todo);
            btnStatus4.setImage(R.drawable.ic_order_status_todo);
            txtvStatus.setText("待接单");
            llayoutInstall.setVisibility(View.GONE);
            llayoutService.setVisibility(View.GONE);
        }
    }

    //显示订单信息
    private void showOrderItemInfo(OrderItemInfo orderItemInfo) {
        LinearLayout llayoutInfo = (LinearLayout)llayoutOrder.getChildAt(1);
        TextView textView1 = (TextView) llayoutInfo.getChildAt(0);
        TextView textView2 = (TextView) llayoutInfo.getChildAt(1);
        TextView textView3 = (TextView) llayoutInfo.getChildAt(2);
        TextView textView4 = (TextView) llayoutInfo.getChildAt(3);
        TextView textView5 = (TextView) llayoutInfo.getChildAt(4);
        TextView textView6 = (TextView) llayoutInfo.getChildAt(5);
        TextView textView7 = (TextView) llayoutInfo.getChildAt(6);
        TextView textView8 = (TextView) llayoutInfo.getChildAt(7);
        if(orderItemInfo != null) {
            llayoutOrder.setVisibility(View.VISIBLE);
            String orderNoStr = orderItemInfo.getOrderno();
            orderNoStr = orderNoStr != null && !orderNoStr.trim().equalsIgnoreCase("") ? orderNoStr : "[XXXXXX]";
            textView1.setText("工单编号 : " + orderNoStr);
            String installItemStr = orderItemInfo.getShopname();
            installItemStr = installItemStr != null && !installItemStr.trim().equalsIgnoreCase("") ? installItemStr : "[XXX]";
            textView2.setText("安装项目 : " + installItemStr);
            String installLengthStr = orderItemInfo.getOrdersum() + orderItemInfo.getSumnuit();
            textView3.setText("安装长度 : " + installLengthStr);
            String installMethodStr = orderItemInfo.getServicemethod();
            textView4.setText("安装方式 : " + installMethodStr);
            String telephoneStr = orderItemInfo.getPhone();
            textView5.setText("联系电话 : " + telephoneStr);
            String materialStr = orderItemInfo.getMaterialname();
            textView6.setText("安装材质 : " + materialStr);
            String customerStr = orderItemInfo.getName();
            textView7.setText("客户姓名 : " + customerStr);
            String timeStr = orderItemInfo.getCreatetime();
            textView8.setText("发布安装时间 : " + timeStr);
        } else {
            llayoutOrder.setVisibility(View.GONE);
        }
    }

    //显示订单过程信息
    private void showOrderServiceInfo(OrderServiceInfo serviceInfo) {
        LinearLayout llayoutInfo = (LinearLayout)llayoutService.getChildAt(1);
        TextView textView1 = (TextView) llayoutInfo.getChildAt(0);
        TextView textView2 = (TextView) llayoutInfo.getChildAt(1);
        if(serviceInfo != null) {
            String startTimeStr = serviceInfo.getStartetime();
            String endTimeStr = serviceInfo.getEndtime();
            if((startTimeStr == null || startTimeStr.trim().equalsIgnoreCase("")) &&
                    (endTimeStr == null || endTimeStr.trim().equalsIgnoreCase(""))) {
                llayoutService.setVisibility(View.GONE);
            } else {
                llayoutService.setVisibility(View.VISIBLE);
                textView1.setText("签到时间 : " + startTimeStr);
                textView2.setText("签退时间 : " + endTimeStr);
            }
        } else {
            llayoutService.setVisibility(View.GONE);
        }
    }

    //显示安装人员信息
    private void showOrderMasterInfo(OrderMasterInfo masterInfo) {
        LinearLayout llayoutMaster = (LinearLayout)llayoutInstall.getChildAt(1);
        ImageView imgvAvatar = (ImageView) llayoutMaster.getChildAt(0);
        LinearLayout llayoutInfo = (LinearLayout) llayoutMaster.getChildAt(1);
        TextView textView1 = (TextView) llayoutInfo.getChildAt(0);
        TextView textView2 = (TextView) llayoutInfo.getChildAt(1);
        TextView textView3 = (TextView) llayoutInfo.getChildAt(2);
        ImageView imgvPhone = (ImageView) llayoutMaster.getChildAt(2);
        if(masterInfo != null) {
            llayoutInstall.setVisibility(View.VISIBLE);
            String avatarStr = masterInfo.getMasteravatar();
            if(avatarStr != null) {
                String imageUrl = ImageLoader.getInstance().getImageUrl(avatarStr);
                ImageLoader.getInstance().displayHeaderPic(OrderDetailActivity.this, imageUrl, imgvAvatar);
            } else {
                ImageLoader.getInstance().displayImageById(OrderDetailActivity.this, R.drawable.ic_message_avatar, imgvAvatar);
            }
            String masterName = masterInfo.getMastername();
            final String telephoneStr = masterInfo.getMasterphone();
            String addressStr = masterInfo.getMasteraddress();
            textView1.setText("" + masterName);
            textView2.setText("联系方式 : " + telephoneStr);
            textView3.setText("地址 : " + addressStr);
            imgvPhone.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //师傅联系电话
                    callMasterPhone(telephoneStr);
                }
            });
        } else {
            llayoutInstall.setVisibility(View.GONE);
        }
    }

    //拨打师傅电话
    private void callMasterPhone(String phoneNumber) {
        if (ContextCompat.checkSelfPermission(OrderDetailActivity.this,
                Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED){
            //没有获得授权，申请授权
            if (ActivityCompat.shouldShowRequestPermissionRationale(OrderDetailActivity.this,
                    Manifest.permission.CALL_PHONE)) {
                Toast.makeText(OrderDetailActivity.this, "请授权！", Toast.LENGTH_LONG).show();
                // 帮跳转到该应用的设置界面，让用户手动授权
                Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                Uri uri = Uri.fromParts("package", OrderDetailActivity.this.getPackageName(), null);
                intent.setData(uri);
                OrderDetailActivity.this.startActivity(intent);
            } else{
                // 不需要解释为何需要该权限，直接请求授权
                ActivityCompat.requestPermissions(OrderDetailActivity.this,
                        new String[]{Manifest.permission.CALL_PHONE}, 500);
            }
        } else {
            // 已经获得授权，可以打电话
            String telephone = phoneNumber;
            Intent intent = new Intent(Intent.ACTION_CALL);
            Uri data = Uri.parse("tel:" + telephone);
            intent.setData(data);
            OrderDetailActivity.this.startActivity(intent);
        }
    }

    //显示订单备注信息
    private void showOrderRemarkInfo(OrderRemarkInfo remarkInfo) {
        LinearLayout llayoutInfo = (LinearLayout)llayoutRemark.getChildAt(1);
        TextView textView1 = (TextView) llayoutInfo.getChildAt(0);
        LinearLayout llayoutImage = (LinearLayout) llayoutInfo.getChildAt(1);
        ImageView imageView1 = (ImageView) llayoutImage.getChildAt(0);
        ImageView imageView2 = (ImageView) llayoutImage.getChildAt(1);
        ImageView imageView3 = (ImageView) llayoutImage.getChildAt(2);

        if(remarkInfo != null) {
            String remarkStr = remarkInfo.getMemo();
            String imageStr = remarkInfo.getImgname();
            if((remarkStr == null || remarkStr.trim().equalsIgnoreCase("")) &&
                    (imageStr == null || imageStr.trim().equalsIgnoreCase(""))) {
                llayoutRemark.setVisibility(View.GONE);
            } else {
                llayoutRemark.setVisibility(View.VISIBLE);
                textView1.setText(remarkStr);
                String[] imageUrls = imageStr.split(",");
                if(imageUrls != null && imageUrls.length > 0) {
                    if(imageUrls.length >= 3) {
                        imageView1.setVisibility(View.VISIBLE);
                        imageView2.setVisibility(View.VISIBLE);
                        imageView3.setVisibility(View.VISIBLE);
                        String imageUrl1 = ImageLoader.getInstance().getImageUrl(imageUrls[0]);
                        String imageUrl2 = ImageLoader.getInstance().getImageUrl(imageUrls[1]);
                        String imageUrl3 = ImageLoader.getInstance().getImageUrl(imageUrls[2]);
                        ImageLoader.getInstance().displayImage(OrderDetailActivity.this, imageUrl1, imageView1);
                        ImageLoader.getInstance().displayImage(OrderDetailActivity.this, imageUrl2, imageView2);
                        ImageLoader.getInstance().displayImage(OrderDetailActivity.this, imageUrl3, imageView3);
                    } else if(imageUrls.length == 2) {
                        imageView1.setVisibility(View.VISIBLE);
                        imageView2.setVisibility(View.VISIBLE);
                        imageView3.setVisibility(View.INVISIBLE);
                        String imageUrl1 = ImageLoader.getInstance().getImageUrl(imageUrls[0]);
                        String imageUrl2 = ImageLoader.getInstance().getImageUrl(imageUrls[1]);
                        ImageLoader.getInstance().displayImage(OrderDetailActivity.this, imageUrl1, imageView1);
                        ImageLoader.getInstance().displayImage(OrderDetailActivity.this, imageUrl2, imageView2);
                    } else {
                        imageView1.setVisibility(View.VISIBLE);
                        imageView2.setVisibility(View.INVISIBLE);
                        imageView3.setVisibility(View.INVISIBLE);
                        String imageUrl1 = ImageLoader.getInstance().getImageUrl(imageUrls[0]);
                        ImageLoader.getInstance().displayImage(OrderDetailActivity.this, imageUrl1, imageView1);
                    }
                }
            }
        } else {
            llayoutRemark.setVisibility(View.GONE);
        }
    }

    //获取订单详情
    class GetOrderDetailInfo extends AsyncTask<String, Void, OrderDetailInfo> {

        public GetOrderDetailInfo() {
            super();
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            if(mLoadingDialog == null) {
                mLoadingDialog = new CustomLoadingDialog(OrderDetailActivity.this);
            }
            mLoadingDialog.setMessage("正在获取订单详情...");
            mLoadingDialog.show();
        }

        @Override
        protected OrderDetailInfo doInBackground(String... params) {
            String orderId = params[0];
            Map<String, String> paramMap = new HashMap<String, String>();
            paramMap.put("orderid", orderId);
            OrderDetailInfo orderInfo = AppService.getInstance().getOrderDetailInfo(paramMap);
            return orderInfo;
        }

        @Override
        protected void onPostExecute(OrderDetailInfo orderInfo) {
            super.onPostExecute(orderInfo);
            if(mLoadingDialog != null) {
                mLoadingDialog.dismiss();
                mLoadingDialog = null;
            }
            if(orderInfo != null) {
                //TODO -- 订单详情
                OrderItemInfo orderItemInfo = orderInfo.getOrderinfo();
                showOrderItemInfo(orderItemInfo);
                OrderServiceInfo serviceInfo = orderInfo.getServicepro();
                showOrderServiceInfo(serviceInfo);
                OrderMasterInfo masterInfo = orderInfo.getMasterInfo();
                showOrderMasterInfo(masterInfo);
                OrderRemarkInfo remarkInfo = orderInfo.getMemo();
                showOrderRemarkInfo(remarkInfo);
            } else {
                showOrderItemInfo(null);
                showOrderServiceInfo(null);
                showOrderMasterInfo(null);
                showOrderRemarkInfo(null);
            }
        }
    }
}
